package fr.epsi.spring1.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import fr.epsi.spring1.dao.UserDao;
import fr.epsi.spring1.domain.User;
import fr.epsi.spring1.service.UserManager;

public class UserManagerImpl implements UserManager {

	private UserDao userDao;

	@Override
	public void delete(User user) {
		if (userDao.getUser(user.getLogin()) != null) {
			userDao.delete(user);
		}
	}

	@Override
	public User getUser(String login) {
		return userDao.getUser(login);
	}

	@Override
	public boolean insert(User user) {
		if (userDao.getUser(user.getLogin()) == null) {
			return userDao.insert(user);
		} else {
			return false;
		}
	}

	@Override
	public boolean isAutorized(User user) {
		User existingUser = userDao.getUser(user.getLogin());
		if (existingUser == null) {
			return false;
		} else if (!user.getPassword().equals(existingUser.getPassword())) {
			return false;
		} else {
			if (user.getLoginHistory() != null && user.getLoginHistory().getLastLogin() != null) {
				long oneMonth = 30 * 24 * 60 * 1000;
				Timestamp lastMonth = new Timestamp(new Date().getTime() - oneMonth);
				if (user.getLoginHistory().getLastLogin().before(lastMonth)) {
					return false;
				}
			}
			userDao.updateLastLogin(user);
			return true;
		}
	}

	@Override
	public List<User> select() {
		return userDao.select();
	}

	@Override
	public void update(User user) {
		User existingUser = userDao.getUser(user.getLogin());
		if (existingUser != null) {
			userDao.update(user);
		}
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public Double getNbUsers() {
		return userDao.getNbUsers();
	}

}
